package com.sumainfor.pc.epc.service.impl.gmio;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.qiniu.util.Json;
import com.sumainfor.common.UnionPay.MapUtil;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.ObjectUtil;
import com.sumainfor.pc.epc.dao.NoRepairOrderMapper;
import com.sumainfor.pc.epc.feign.Zfeign.ZpcMktFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.sumainfor.common.util.ObjectUtil.converStringForArray;

/**
 * <p>
 * 运营部调用
 * <p>
 *
 * @author: zhoucong
 * @create: 2019-06-08 16:45
 **/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class NoRepairOrderService implements Serializable {

    @Autowired
    NoRepairOrderMapper noRepairOrderMapper;


    @Autowired
    private ZpcMktFeign mktFeign;

    /**
     * <p>
     * 超过72小时未维修
     * </p>
     *
     * @author: zhoucong
     * @since:
     */
    public JsonResult getNoRepairOrderCount(Map<String,Object> params) {
        JsonResult result = new JsonResult();
        Map<String, Object> map = new HashMap<>();
        List<Map<String,Object>> getNoRepairOrderCount = noRepairOrderMapper.getNoRepairOrderCount();
        int cout = 0;
        if (getNoRepairOrderCount !=null&&getNoRepairOrderCount.size()>0){
            for (Map<String,Object> RepairMap:getNoRepairOrderCount) {
                if (RepairMap.get("HouId")!=null){
                    RepairMap.put("SysUserId",MapUtils.getString(params,"user_id"));
                    JsonResult zpcMktResult = mktFeign.getTcmktHousSysUserId(RepairMap);
                    Map<String,ObjectUtil> zpcMktMap = (Map<String, ObjectUtil>) zpcMktResult.get("result");
                    if(MapUtils.getInteger(zpcMktMap,"SysUserIdCount")>0){
                        cout = cout+1;
                    }
                }
            }

 map.put("getNoRepairOrderCount",cout);

        }else{
            map.put("getNoRepairOrderCount",0);
        }
        return result.put(map);
    }

    /**
     * <p>
     * 待验收
     * </p>
     *
     * @author: zhoucong
     * @since:
     */
    public JsonResult getQuarantinedRoomCount(Map<String,Object> params) {
        JsonResult result = new JsonResult();
        params.put("SysUserId",params.get("user_id"));
        Map<String, Object> map = new HashMap<>();
        map.put("getQuarantinedRoomCount", noRepairOrderMapper.getQuarantinedRoomCount(params));
        return result.put(map);
    }

    /**
     * <p>
     * 维修工单跟踪
     * </p>
     *
     * @author: zhoucong
     * @since:
     */
    public JsonResult getRepairTracking(Map<String,Object> params) {
            JsonResult result = new JsonResult();
        Map<String, Object> map = new HashMap<>();
     //   List<String> HouIdList = new ArrayList<>();
        List<Map<String,Object>> getRepairTracking = noRepairOrderMapper.getRepairTracking();
       // mktFeign.getTcmktHousSysUserId
        int cout = 0 ;
        if (getRepairTracking!=null&&getRepairTracking.size()>0){
            for (Map<String,Object> RepairMap:getRepairTracking) {
                if (RepairMap.get("HouId")!=null){
                  //  HouIdList.add(MapUtils.getString(RepairMap,"HouId"));
                    RepairMap.put("SysUserId",MapUtils.getString(params,"user_id"));
                    JsonResult zpcMktResult = mktFeign.getTcmktHousSysUserId(RepairMap);
                    Map<String,ObjectUtil> zpcMktMap = (Map<String, ObjectUtil>) zpcMktResult.get("result");
                    if(MapUtils.getInteger(zpcMktMap,"SysUserIdCount")>0){
                        cout = cout+1;
                    }
                }
            }
            map.put("getRepairTracking",cout);

        }else{
            map.put("getRepairTracking",0);
        }
   return result.put(map);

    }

    /**
     * 租后主管工作台查询超72小时未维修工单
     * @author zhoucong
     * @data 2019/7/3
     * @Param
     * @return
     */
    public JsonResult getNoRepairOrderInteger(){
        JsonResult result = new JsonResult();
        Map<String,Object> map = new HashMap<>();
        map.put("getNoRepairOrderInteger",noRepairOrderMapper.getNoRepairOrderInteger());
        return result.put(map);
    }



    /**
     * 装修明细报表
     *
     * @param page
     * @param params
     * @return
     */
    public Page<Map<String, Object>> getPlanDetailTable(Page page, Map<String, Object> params) {
        //存储的是房源主集合
        List<String> hIds = Lists.newArrayList();
        params.put("hIds", hIds);
        //获取房源主编号
        String formHId = MapUtils.getString(params, "formHId");
        //获取项目编号
        String comId = MapUtils.getString(params, "comId");
        //获取服务中心编号
        String centerId = MapUtils.getString(params, "centerId");
        //获取所属公司编号
        String areaId = MapUtils.getString(params, "areaId");

        if (StringUtils.isNotBlank(formHId)) {
            hIds.addAll(ObjectUtil.converStringForArray(formHId));
        } else if (StringUtils.isNotBlank(comId)) {
            Set<String> houId = noRepairOrderMapper.selectPlanHId().stream().collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(houId)) {
                return page;
            }
            //查询房源的所属项目编号
            List<String> comIdList = converStringForArray(comId);
            List<String> hList = Lists.newArrayList();
            for (String s : comIdList) {
                JsonResult<List<String>> result = mktFeign.selectComIdByHId(CustomMap.create("hIds", houId)
                        .put("val", s)
                        .put("col", "hmain.HouId")
                        .put("where", "community.ComId")
                );
                if (!result.isSuccess()) {
                    throw new TCException("异常:" + result.getErrorMessage());
                }
                hList.addAll(result.getResult());
            }
        } else if (StringUtils.isNotBlank(centerId)) {
            Set<String> houId = noRepairOrderMapper.selectPlanHId().stream().collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(houId)) {
                return page;
            }
            List<String> centerIdList = converStringForArray(centerId);
            List<String> hList = Lists.newArrayList();
            //查询房源的编号根据服务中心编号
            for (String id : centerIdList) {
                JsonResult<List<String>> result = mktFeign.selectComIdByHId(CustomMap.create("hIds", houId)
                        .put("val", id)
                        .put("col", "hmain.HouId")
                        .put("where", "community.MiId")
                );
                if (!result.isSuccess()) {
                    throw new TCException("异常:" + result.getErrorMessage());
                }
                hList.addAll(result.getResult());
            }
            if (CollectionUtils.isEmpty(hList)) {
                return page;
            }
            hIds.addAll(hList);
        } else if (StringUtils.isNotBlank(areaId)) {
            Set<String> houId = noRepairOrderMapper.selectPlanHId().stream().collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(houId)) {
                return page;
            }

            List<String> areaIdList = converStringForArray(areaId);
            List<String> hList = Lists.newArrayList();
            //查询房源的编号根据服务中心编号
            for (String id : areaIdList) {
                JsonResult<List<String>> result = mktFeign.selectComIdByHId(CustomMap.create("hIds", houId)
                        .put("val", id)
                        .put("col", "hmain.HouId")
                        .put("where", "hmain.CorId")
                );
                if (!result.isSuccess()) {
                    throw new TCException("异常:" + result.getErrorMessage());
                }
                hList.addAll(result.getResult());
            }
            if (CollectionUtils.isEmpty(hList)) {
                return page;
            }
            hIds.addAll(hList);
        }

        List<Map<String, Object>> dataPage = noRepairOrderMapper.selectPlanDetailTable(params);

        if (CollectionUtils.isEmpty(dataPage)) {
            return page;
        }


        //合并 首先根据批次进行分组
        Map<String, List<Map<String, Object>>> eqPlan = Maps.newHashMap();
        for (Map<String, Object> map : dataPage) {
            String planId = MapUtils.getString(map, "PlansId");
            List<Map<String, Object>> itemList;
            if (eqPlan.containsKey(planId)) {
                itemList = eqPlan.get(planId);
            } else {
                itemList = Lists.newArrayList();
                eqPlan.put(planId, itemList);
            }
            itemList.add(map);
        }

        //合并 根据房源进行分组
        List<Map<String, Object>> dataResult = Lists.newArrayList();
        for (Map.Entry<String, List<Map<String, Object>>> entry : eqPlan.entrySet()) {
            //相同的房源合并一起
            Map<String, ArrayList<Map<String, Object>>> eqHou = Maps.newHashMap();
            for (Map<String, Object> map : entry.getValue()) {
                String houId = MapUtils.getString(map, "HouId");
                ArrayList<Map<String, Object>> itemList;
                if (eqHou.containsKey(houId)) {
                    itemList = eqHou.get(houId);
                } else {
                    itemList = Lists.newArrayList();
                    eqHou.put(houId, itemList);
                }
                itemList.add(map);
            }

            //分组供应商
            for (Map.Entry<String, ArrayList<Map<String, Object>>> houEntity : eqHou.entrySet()) {
                Map<String, Object> dataItem = Maps.newHashMap();
                dataItem.putAll(houEntity.getValue().get(0));
                dataItem.remove("SupId");
                dataItem.remove("moneySum");
                List<Map<String, Object>> supList = Lists.newArrayList();
                dataItem.put("supList", supList);
                for (Map<String, Object> map : houEntity.getValue()) {
                    supList.add(CustomMap.create().put("SupId", MapUtils.getString(map, "SupId")).put("moneySum", map.get("moneySum")));
                }
                //添加到总数据集合中
                dataResult.add(dataItem);
            }

        }

        if (page.getSize() < 0) {
            return page.setRecords(this.setHousingFillDataInfo(dataResult));
        }

        //进行分页操作
        page.setTotal(dataResult.size());
        if (page.getTotal() <= 0) {
            return page;
        }
        if (page.getTotal() % page.getSize() > 0) {
            page.setPages((page.getTotal() / page.getSize()) + 1);
        } else {
            page.setPages(page.getTotal() / page.getSize());
        }
        List<Map<String, Object>> collect = dataResult.stream().skip(((page.getCurrent() - 1) * page.getSize())).limit(page.getSize()).collect(Collectors.toList());
        page.setRecords(this.setHousingFillDataInfo(collect));
        return page;
    }

    /**
     * 填充数据到集合Map中 并且根据供应商分组操作下列
     *
     * @param dataList
     */
    private List<Map<String, Object>> setHousingFillDataInfo(List<Map<String, Object>> dataList) {

        String regEx = "[^a-zA-Z0-9]";

        //获取房源信息根据主编号
        Set<String> hIdSets = dataList.stream().map(item -> MapUtils.getString(item, "HouId")).collect(Collectors.toSet());
        JsonResult<List<Map<String, Object>>> detailJson = mktFeign.selectHousingDetailByArray(hIdSets);
        if (!detailJson.isSuccess()) {
            throw new TCException("错误：" + detailJson.getErrorMessage());
        }

        Map<String, Object> colAndRow = Maps.newHashMap();
        List<Map<String, Object>> colList = Lists.newArrayList();
        List<Map<String, Object>> rowList = Lists.newArrayList();
        colAndRow.put("col", colList);
        colAndRow.put("row", rowList);

        colList.add(CustomMap.create("key", "ComName").put("name", "小区名称"));
        colList.add(CustomMap.create("key", "Br").put("name", "房号"));
        colList.add(CustomMap.create("key", "areaName").put("name", "隶属公司"));
        colList.add(CustomMap.create("key", "PlansId").put("name", "批次单号"));
        colList.add(CustomMap.create("key", "PlansSupName").put("name", "施工方"));
        colList.add(CustomMap.create("key", "CheckRealityTime").put("name", "完工日期"));
        colList.add(CustomMap.create("key", "Area").put("name", "房型大小"));
        colList.add(CustomMap.create("key", "SumPrice").put("name", "合计"));

        Set<String> supIdList = Sets.newHashSet();
        for (Map<String, Object> map : dataList) {
            for (Map<String, Object> detailItem : detailJson.getResult()) {
                if (Objects.equals(MapUtils.getString(map, "HouId"), MapUtils.getString(detailItem, "HouId"))) {
                    map.putAll(detailItem);
                    break;
                }
            }

            //添加硬装供应商编号
            supIdList.add((String) map.get("ySup"));

            //总价
            BigDecimal sum = new BigDecimal("0");
            sum = sum.add(ObjectUtil.convertBigDecimal(map.get("yPrice")));

            List<Map<String, Object>> supList = (List<Map<String, Object>>) map.get("supList");
            for (Map<String, Object> sup : supList) {
                supIdList.add((String) sup.get("SupId"));
                sum = sum.add(ObjectUtil.convertBigDecimal(sup.get("moneySum")));
            }
            CustomMap rowItem = CustomMap.create("ComName", map.get("ComName"))
                    .put("Br", map.get("Building") + "#" + map.get("Room"))
                    .put("areaName", map.get("areaName"))
                    .put("PlansId", map.get("PlansId"));


            //查询施工方信息
            List<Map<String, Object>> planSupData = noRepairOrderMapper.selectSupInfoBySupList(Sets.newHashSet(MapUtils.getString(map, "ySup")));
            rowItem.put("PlansSupName", planSupData.get(0).get("UnitName"));
            rowItem.put("CheckRealityTime", map.get("CheckRealityTime"));
            rowItem.put("Area", map.get("Area"));
            rowItem.put("SumPrice", sum);
            rowItem.put("flag", String.format("%s%s", map.get("HouId"), map.get("PlansId")));
            rowList.add(rowItem);
        }
        //查询获得供应商信息
        List<Map<String, Object>> supInfoList = noRepairOrderMapper.selectSupInfoBySupList(supIdList);

        for (Map<String, Object> supItem : supInfoList) {
            colList.add(CustomMap.create("key", String.format("Sup%s", MapUtils.getString(supItem, "SupId").replaceAll(regEx, "")))
                    .put("name", supItem.get("UnitName"))
                    .put("statistics", true)
            );
        }

        //将新列匹配上 不包含硬装供应商
        for (Map<String, Object> map : dataList) {
            List<Map<String, Object>> supList = (List<Map<String, Object>>) map.get("supList");

            for (Map<String, Object> rowItem : rowList) {
                if (Objects.equals(MapUtils.getString(rowItem, "flag"), String.format("%s%s", map.get("HouId"), map.get("PlansId")))) {
                    //添加普通商品的
                    for (Map<String, Object> sup : supList) {
                        rowItem.put(String.format("Sup%s", MapUtils.getString(sup, "SupId").replaceAll(regEx, "")), sup.get("moneySum"));
                    }
                    //添加硬装对应价格
                    rowItem.put(String.format("Sup%s", MapUtils.getString(map, "ySup").replaceAll(regEx, "")), map.get("yPrice"));
                    rowItem.remove("flag");
                    break;
                }
            }

        }
        return Lists.newArrayList(colAndRow);
    }

}
